<template>
  <el-container style="position: relative">
    <SiteTree style="position: fixed" @on-choose-region="filetrStation" />
    <el-main class="realTimeDataContent">
      <el-card class="lg-mb-20">
        <div
          class="default-main"
          style="
            display: flex;
            justify-content: flex-start;
            align-items: center;
          "
        >
          <!-- 表格与图表切换 -->
          <el-radio-group v-model="radio1" @change="changeDiffWayShowData">
            <el-radio label="数据" border>数据</el-radio>
            <el-radio label="图表" border>图表</el-radio>
          </el-radio-group>
          <!-- <div style="width: 20%; margin-left: 5%">
            <el-radio-group v-model="radio2" @change="changeDiffType">
              <el-radio label="卧式" border>卧式</el-radio>
              <el-radio label="立式" border>立式</el-radio>
            </el-radio-group>
          </div> -->
          <!-- 字段组选择 -->
          <el-select
            v-model="realTime.history"
            @change="changeFileds"
            style="margin-left: 5%"
          >
            <el-option
              v-for="item in realTime.horizontalFields"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictLabel"
            />
          </el-select>
          <!-- 时间选择 -->
          <!-- <div style="width: 20%; margin-left: 5%">
            <el-date-picker
              class="datetime-picker"
              v-model="state.stateTime"
              :disabled-date="pickerOptions"
              type="datetimerange"
              disabled
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </div> -->
        </div>
        <!-- 图表数据 -->
        <Echarts v-if="state.EchartsShow" ref="EchartsRef" />
        <!-- 表格数据 -->
        <RealTime v-if="state.realTimeShow" ref="RealTimeRef" />
        <div v-if="state.titleShow">请选择左侧站点</div>
      </el-card>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import {
  reactive,
  onMounted,
  computed,
  provide,
  ref,
  onBeforeUnmount,
} from "vue";
import SiteTree from "./components/aside.vue";
import { useAssetSite } from "@/store/backend/Assets/site";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import RealTime from "./components/realTimeContent.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useElectricData } from "@/store/backend/DataM/RealTime";
import { useWarningItemObject } from "@/store/backend/Warning/itemObject";
import { useAssetCabinet } from "@/store/backend/Assets/cabinet";
import { DictOperation, TimeOfPeriod, timeFormat } from "@/utils/common"; // 导入表格api方法生成器
import useCurrentInstance from "@/utils/useCurrentInstance";
import Echarts from "./components/echarts.vue";

const site = useAssetSite();
const config = useConfig();
const dictionary = useDictionary();
const realTime = useElectricData();
const cabinet = useAssetCabinet();
const itemObject = useWarningItemObject();
const RealTimeRef = ref();

const radio1 = ref("数据");
const radio2 = ref("卧式");

const state: {
  realTimeShow: boolean;
  EchartsShow: boolean;
  titleShow: boolean;
  comSearch: any;
  stateTime: any[];
  isOpen: boolean;
} = reactive({
  realTimeShow: false,
  EchartsShow: false,
  titleShow: true,
  comSearch: { form: {} },
  stateTime: [],
  isOpen: false,
});

//全局事件总线
const { proxy } = useCurrentInstance();

//限制用户选择日期
const pickerOptions = (time: Date) => {
  // return time.getTime() > Date.now() - 1 * 24 * 60 * 60 * 1000;
  return time.getTime() > Date.now();
};

//重写获取当月第一天的方法
class NewTimeOfPeriod extends TimeOfPeriod {
  getStart(): any {
    let date = new Date();
    date.setDate(1);
    // let startDay = date.toLocaleDateString().replace(/\//g, "-");
    let startDay =
      date.getFullYear() +
      "-" +
      JSON.stringify(date.getMonth() + 1).padStart(2, "0") +
      "-" +
      JSON.stringify(date.getDate()).padStart(2, "0");
    startDay = startDay + " 00:00";
    console.log("重写获取当月第一天的方法", startDay);
    return startDay;
  }
}
const newTimeFunc = new NewTimeOfPeriod();

//初始化字典处理类
const dictOperation = new DictOperation();
//重写字典处理
type dictObj = (arr: any[]) => anyObj;
class NewDictOperation extends DictOperation {
  getDictData: dictObj = (arr: any[]) => {
    let obj: any = {};
    for (let i = 0, len = arr.length; i < len; i++) {
      obj[arr[i].dictLabel] = arr[i].remark;
    }
    return obj;
  };
  //获取字典
  getDictionary = (
    specificClass: any, //pinia仓库类
    dictText: string, //字典名称
    filed: string, //仓库存储的经过处理后的字典对象
    dictStore: string //仓库存储的原始字典数组
  ) => {
    if (
      JSON.stringify(specificClass.tags) == "{}" ||
      !(filed == "" ? true : specificClass.tags[filed]) ||
      JSON.stringify(dictionary.moreTags[dictText]) == "{}"
    ) {
      dictionary.getDictInfo(dictText).then((res: any) => {
        let tempTags = dictOperation.getDictData(res);
        dictionary.moreTags[dictText] = tempTags;
        specificClass.$patch((state: any) => {
          if (filed != "") {
            state.tags[filed] = tempTags;
          }
          state.typeCategoryFormat = this.getDictData(res);
          state.horizontalFields = res;
          state[dictStore] = res;
          realTime.history = res[0].dictLabel;
        });
      });
    } else {
      realTime.history = realTime.horizontalFields[0].dictLabel;
    }
  };
}
const newDictOperation = new NewDictOperation();

//刷新数据
const refreshData = () => {
  //如果一开始没选择站点不显示右侧table表
  if (state.isOpen && state.realTimeShow) {
    RealTimeRef.value.getRealTimeLast();
    state.realTimeShow = false;
    setTimeout(() => {
      state.realTimeShow = true;
    }, 500);
  } else if (state.isOpen && state.EchartsShow) {
    state.EchartsShow = false;
    setTimeout(() => {
      state.EchartsShow = true;
    }, 500);
  } else {
    state.titleShow = false;
    state.isOpen = true;
    state.realTimeShow = true;
  }
};

//接收站点树传递过来的数据
const filetrStation = (row: any, node: any) => {
  console.log("接收站点树传递过来的数据", row, node);
  if (node) {
    realTime.siteIds = node.checkedKeys;
  }
  //刷新数据
  refreshData();
};

//选择不同方法展示数据
const changeDiffWayShowData = (value: any) => {
  console.log("选择不同方法展示数据", value);
  if (state.isOpen && value === "图表") {
    state.titleShow = false;
    state.EchartsShow = true;
    state.realTimeShow = false;
  }
  if (state.isOpen && value === "数据") {
    state.titleShow = false;
    state.realTimeShow = true;
    state.EchartsShow = false;
  }
};

//选择不同字段组显示
const changeFileds = (value: any) => {
  console.log("选择不同字段组显示", value, typeof value);
  if (state.isOpen && radio1.value === "数据") {
    state.realTimeShow = false;
    state.EchartsShow = false;
    setTimeout(() => {
      state.realTimeShow = true;
    }, 500);
  }
  if (state.isOpen && radio1.value === "图表") {
    state.realTimeShow = false;
    state.EchartsShow = false;
    setTimeout(() => {
      state.EchartsShow = true;
    }, 500);
  }
};

// 获取当前月的第一天与当前时间;
const getTime = () => {
  // state.stateTime[0] = newTimeFunc.getStart();
  state.stateTime[0] = timeFormat("", "yyyy-mm-dd") + " 00:00:00";
  state.stateTime[1] = timeFormat("", "yyyy-mm-dd hh:MM:ss");
  //首次更新仓库存储时间
  realTime.beginTime = state.stateTime[0];
  realTime.endTime = state.stateTime[1];
};
getTime();

//获取机柜类型字典
const getDictionary = () => {
  //获取站点类型的字典
  dictOperation.getDictionary(site, "sys_site_type", "siteType", "type");
  //获取机柜类型的字典
  dictOperation.getDictionary(realTime, "sys_cabinet_type", "type", "type");
  //获取卧式机柜字段组合（与告警类别统一）的字典
  newDictOperation.getDictionary(
    realTime,
    "sys_warning_category",
    "categoryName",
    "cabinetFields"
  );
};
getDictionary();

//获取告警对象列表
const getobjectList = () => {
  itemObject
    .getWarningItemObjectList({ pageSize: 10000 })
    .then((res: any) => {
      itemObject.fullData = res; //所有告警对象数据存储至仓库
    })
    .catch((err: any) => {});
};

const menuWidth = computed(() => config.overviewMenuWidth());

onMounted(() => {
  getobjectList(); //获取告警对象列表
});
provide("site", site);
provide("config", config);
provide("dictionary", dictionary);
provide("realTime", realTime);
provide("itemObject", itemObject);
provide("cabinet", cabinet);

onBeforeUnmount(() => {
  realTime.history = "";
  realTime.isAsc = "desc"; //默认倒序
  realTime.orderByColumn = "createTime"; //默认createTime
});
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 20px var(--ba-main-space);
}
.realTimeDataContent {
  margin-left: v-bind(menuWidth);
}
</style>
